<?php

namespace app\airobot\controller;

use app\airobot\CommonLogic;
use app\airobot\model\BattleBox;
use app\airobot\model\OriginBattleConfig;
use app\airobot\model\OriginForge;
use app\airobot\model\OriginRobotSpinConfig;
use app\airobot\model\UserModel;
use think\admin\Controller;
use think\db\exception\DbException;
use think\facade\Db;
use ZipArchive;

/**
 * 超管系统-赔率监控Battle
 * Class Banner
 * @package app\airobot\controller
 */
class MonitorBattle extends Controller
{
    private $table = 'monitor_battle';
    public $commonLogic;

    /**
     * 赔率监控Battle
     * @auth true
     */
    public function index()
    {
        $this->commonLogic = new CommonLogic();
        $this->title = '赔率监控Battle';
        $query = $this->_query($this->table);
        if (isset($_GET['exec_time']) && $_GET['exec_time'] != "") {
            $dayArr = explode(" - ", $_GET['exec_time']);
            if (count($dayArr) == 2) {
                $query->where('date', '>=', $dayArr[0]);
                $query->where('date', '<=', $dayArr[1]);
            }
        }
        if (isset($_GET['mode']) && $_GET['mode'] != "") {
            $query->where('mode', '=', $_GET['mode']);
        }
        $data = $query->select()->toArray();
        $data = $this->dealData($data);

        $this->list = $data;
        $this->fetch();
    }

    protected function dealData(array $data): array
    {
        $this->commonLogic = new CommonLogic();
        $dataArr = [];
        foreach ($data as $vo) {
            $vo["pool_change_amount"] = $this->commonLogic->DealAmount($vo['pool_change_amount']);
            $vo["pool_transfer_amount"] = $this->commonLogic->DealAmount($vo['pool_transfer_amount']);
            $vo["user_count"] = number_format($vo["user_count"], 0);
            $vo["battle_count"] = number_format($vo["battle_count"], 0);
            $vo["box_count"] = number_format($vo["box_count"], 0);
            $vo["total_true_user_cost_amount"] = $this->commonLogic->DealAmount($vo['total_true_user_cost_amount']);
            $vo["total_true_user_win_amount"] = $this->commonLogic->DealAmount($vo['total_true_user_win_amount']);
            $vo["avg_user_times"] = number_format($vo["avg_user_times"], 2);
            $vo["avg_box_times"] = number_format($vo["avg_box_times"], 2);
            $vo["avg_cost_amount"] = $this->commonLogic->DealAmount($vo['avg_cost_amount']);
            $vo["user_odds"] = number_format($vo["user_odds"], 4);
            $vo["system_profit_amount"] = $this->commonLogic->DealAmount($vo['system_profit_amount']);
            $dataArr[] = $vo;
        }

        return $dataArr;
    }

    /**
     * 导出文件
     * @auth true
     */
    public function export()
    {
        // 获取数据
        $query = Db::table('monitor_battle');
        if (isset($_GET['exec_time']) && $_GET['exec_time'] != "") {
            $dayArr = explode(" - ", $_GET['exec_time']);
            if (count($dayArr) == 2) {
                $query->where('date', '>=', $dayArr[0]);
                $query->where('date', '<=', $dayArr[1]);
            }
        }
        if (isset($_GET['mode']) && $_GET['mode'] != "") {
            $query->where('mode', '=', $_GET['mode']);
        }
        $list = $query->select()->toArray();
        $list = $this->dealData($list);

        // 设置 CSV 文件的名字
        $filename = "monitor_battle.csv";
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '";');
        $output = fopen('php://output', 'w');

        // 写入 CSV 头部
        fputcsv($output, ['日期', '模式', '水池增/减', '抽水', '用户数量', 'Battle次数', '盲盒个数', '用户总押注', '用户总赢钱', '人均Battle次数', '场均盲盒个数', '场均押注', '赔率', '盈利']);

        // 写入数据行
        foreach ($list as $v) {
            fputcsv($output, [
                $v['date'],
                $v['mode'],
                $v['pool_change_amount'],
                $v['pool_transfer_amount'],
                $v['user_count'],
                $v['battle_count'],
                $v['box_count'],
                $v['total_true_user_cost_amount'],
                $v['total_true_user_win_amount'],
                $v['avg_user_times'],
                $v['avg_box_times'],
                $v['avg_cost_amount'],
                $v['user_odds'],
                $v['system_profit_amount']]);
        }

        // 关闭输出流
        fclose($output);
    }

    /**
     * 批量删除
     * @auth true
     */
    public function remove()
    {
        try {
            Db::startTrans();

            Db::table("monitor_battle")->where('id', '>', 0)->delete();
            Db::table("battle")->where('id', '>', 0)->delete();
            Db::table("battle_box")->where('id', '>', 0)->delete();
            Db::table("battle_spin_result")->where('id', '>', 0)->delete();
            Db::table("battle_user_action")->where('id', '>', 0)->delete();
            Db::table("battle_pool_transfer_records")->where('id', '>', 0)->delete();
            Db::table("battle_pool_operate_records")->where('id', '>', 0)->delete();
            Db::table("battle_user_spin_record")->where('id', '>', 0)->delete();
            Db::table("battle_result_records")->where('id', '>', 0)->delete();
            Db::table("battle_pool")->where('id', '>', 0)->delete();
            Db::table("user_spin")->where('battle_id', '>', 0)->delete();

            // 创建水池:NORMAL MODE
            $battlePool = [];
            $battlePool["mode"] = "NORMAL MODE";
            $battlePool["total_amount"] = 0;
            $battlePool["transfer_amount"] = 0;
            $battlePool["operate_amount"] = 0;
            $battlePool["battle_count"] = 0;
            $battlePool["total_true_user_cost_amount"] = 0;
            $battlePool["total_true_user_win_amount"] = 0;
            $battlePool["true_user_odds"] = 0;
            $battlePool["system_profit_amount"] = 0;
            Db::table('battle_pool')->insert($battlePool);

            // 创建水池:SHARE MODE
            $battlePool = [];
            $battlePool["mode"] = "SHARE MODE";
            $battlePool["total_amount"] = 0;
            $battlePool["transfer_amount"] = 0;
            $battlePool["operate_amount"] = 0;
            $battlePool["battle_count"] = 0;
            $battlePool["total_true_user_cost_amount"] = 0;
            $battlePool["total_true_user_win_amount"] = 0;
            $battlePool["true_user_odds"] = 0;
            $battlePool["system_profit_amount"] = 0;
            Db::table('battle_pool')->insert($battlePool);

            // 如果一切正常，提交事务
            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            error_log(var_export($exception->getMessage(), true) . "\n", 3, "/tmp/qp.log");
            $this->error('清空失败');
        }

        $this->success('清空成功');
    }
}